<?php
class Mailaddress extends AppModel {

	var $name = 'Mailaddress';

	//The Associations below have been created with all possible keys, those that are not needed can be removed
	var $belongsTo = array(
			'User' => array('className' => 'User',
								'foreignKey' => 'user_id',
								'conditions' => '',
								'fields' => '',
								'order' => ''
			)
	);
	//バリデート
	var $validate = array(
		'status' => array(
			'rule' => array('isInArray', array('notActive', 'active', 'resign', 'disable')),
		),
		'user_id' => array(
			'rule' => array('isPlusNumber'),
		),
		'ip' => array(
			'rule' =>array('ip'),
		),
		'mailaddress' => array(
			'email' => array(
				'rule' => array('email'),
				'message' => '正しいメールアドレスではありません',
			),
			'duplicate' => array(
				'rule' => array('checkDuplicate', array('status' => '= active')),
				'message' => 'そのメールアドレスは登録されています',
			)
		),
	);
	
	function getUserID($mail)
	{
		return $this->field('user_id', array('mailaddress' => '= '.$mail, 'status' => '= active',));
	}
	
	
	function register($userID, $mailaddress)
	{
		$data = array();
		$data['status'] = 'notActive';
		$data['user_id'] = $userID;
		$data['mailaddress'] = $mailaddress;
		$data['ip'] = $this->RHgetClientIP();
		
		return $this->save(array($this->name => $data));
	}
	
	function checkActivate($token, $mode = 'Mailaddresses')
	{
		//トークンのチェック
		if($mode === 'Mailaddresses'){$salt = Configure::read('salt.activate');}
		elseif($mode === 'Users'){$salt = Configure::read('salt.register');}
		
		if(!$this->data || $token !== md5($salt.strtotime($this->data[$this->name]['modified']))){
			$this->invalidate('mail', 'そんなメール無いです or このメールアドレスは登録済みです');
			return false;
		}
		//メールのステータス
		if($this->data[$this->name]['status'] !== 'notActive'){
			$this->invalidate('notActivate','このメールアドレスはアクティベート対象ではありません');
			return false;
		}
		//登録済みの中に同じメールが無いかどうか
		$cond = array();
		$cond['mailaddress'] = $this->data[$this->name]['mailaddress'];
		$cond['status'] = 'active';
		$cond['id'] = '!= '.$this->data[$this->name]['id'];
		
		if($this->findCount($cond, -1) !== 0){
			$this->invalidate('dupulicate','このメールアドレスはアクティベート済みです');
			return false;
		}
		
		return true;
	}
	

}
?>